package com.hup.sidebar.framework.util;

import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.AsyncTask;
import android.widget.ImageView;

import java.lang.ref.WeakReference;

public class AsyncDrawableTask extends AsyncTask<Void, Void, Drawable> {
    private static final int FADE_IN_TIME = 500;
    private final WeakReference<ImageView> weakReference;

    /**
     * @param imageView 目标view,不能调用 setTag
     */
    public AsyncDrawableTask(ImageView imageView) {
        super();
        //取消旧任务
        AsyncDrawableTask tag = (AsyncDrawableTask) imageView.getTag();
        if (tag != null) tag.cancel(false);

        this.weakReference = new WeakReference<>(imageView);
        imageView.setTag(this);
    }

    /**
     * @param imageView 目标view,不能调用 setTag
     */
    public AsyncDrawableTask(ImageView imageView, Drawable placeholder) {
        this(imageView);
        imageView.setImageDrawable(placeholder);
    }

    @Override
    protected Drawable doInBackground(Void... voids) {
        return null;
    }

    @Override
    public void onPostExecute(Drawable drawable) {
        if (isCancelled()) return;

        ImageView imageView = weakReference.get();
        if (imageView == null) return;

        imageView.setTag(null);
        Drawable placeholder = imageView.getDrawable();
        /*
        内存泄露问题
            上个版本的代码存在明显的内存泄露,狂刷列表时内存会一直增加
        原因
            和AsyncTask没关系!!
            new TransitionDrawable时,直接传入旧的 TransitionDrawable(和它构造时的2个drawable)
            导致 imageView的全部历史setImageDrawable: drawable图标和TransitionDrawable都不能被释放!
        修改后
            狂刷列表时,内存会有非常频繁的上下波动(系统能非常及时和频繁的回收内存)
         */
        if (placeholder instanceof TransitionDrawable) {
            placeholder = ((TransitionDrawable) placeholder).getDrawable(1);//只取上次的图标
        }
        TransitionDrawable transitionDrawable = new TransitionDrawable(new Drawable[]{placeholder, drawable});
        imageView.setImageDrawable(transitionDrawable);
        transitionDrawable.setCrossFadeEnabled(true);
        transitionDrawable.startTransition(FADE_IN_TIME);
    }
}